function uploadFile() {
    const fileInput = document.getElementById('publish_url');
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);

    fetch('http://localhost:8080/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if(response.ok) {
            return response.json(); // 将响应转换为 JSON 格式
        } else {
            throw new Error('文件上传失败');
        }
    })
    .then(data => {

       
       // 图片加载完成后，将其添加到预览区域
       const previewImg = document.createElement('img');
       previewImg.src = "http://localhost:8080/download/" + data.data;
       previewImg.id = data.data
       previewImg.classList.add('preview-image');

       const previewSection = document.getElementById('preview-section-id');
       previewSection.appendChild(previewImg);
    
        // 文件上传成功
        console.log('文件上传成功');
    })
    .catch(error => {
        console.error('上传出错:', error);
    });
}

function publish() {  
    var title = $('#title').val();  
    var description = $('#description').val();  
    var imageIds = getAllImageIds();  
    var token = localStorage.getItem("token");  

    $.ajax({  
        url: 'http://localhost:8080/publish',  
        type: 'POST',  
        contentType: 'application/json',  
        headers: {  
            'Authorization': token  // 如果需要 Bearer 前缀  
        },  
        data: JSON.stringify({  
            title: title,  
            description: description,  
            imageIds: imageIds  
        }),  
        success: function(data) {  
            console.log(data);  
            window.location.href = '问答.html';  
        },  
        error: function(xhr, status, error) {  
            console.error('Error publishing:', xhr.responseText);  
        }  
    });  
}

function getAllImageIds() {  
    const previewSection = document.getElementById('preview-section-id');  
    const imgElements = previewSection.querySelectorAll('img'); // 获取所有img标签  
    const imageIds = []; // 用于存储所有图片ID的数组  
    
    imgElements.forEach(img => {  
        // 假设图片的src属性格式总是 "http://localhost:8080/download/{id}"  
        const imageId = img.id;  
            // 如果匹配成功，将ID添加到数组中  
            imageIds.push(imageId);  
    });  
    
    return imageIds; // 返回包含所有图片ID的数组  
}  
